// 开发
// @charset "utf-8"
var app
var cocoTimer2 = '';
const staticLocation = '//s.thsi.cn/cd/b2cweb_vis_phpcx/chargeapp/css/indexintelligent/'

let popperInstance // popper全局对象

let hasCpmj = false;

var watchProgress = 0 // 观看进度全局变量

var cfqhDisabled = true // 财富启航是否禁用全局变量

var vtuberRight=0;
var vtuberTop=0;

// 皮肤颜色
//  Gold = '0', 土豪金皮肤
// Blud = '1',  高雅蓝皮肤
// Jadeite = '2',  翡翠金
// Metal = '3'   金属蓝
var avatarType='0'

var instructionPopperInfo = {
  // 是否对用户展示 弹窗
  isUserOk: false,
  // 弹窗挂载元素是否是否已稳定
  isTextOk: false,
  // 切换皮肤时会重新触发动画，动画进而重载弹窗，但用户访问次数不会因此+1；showNums判断弹窗是否为第一次显示；0表示第一次。非0表示第二次
  showNums: 0,
  // 弹窗挂载元素
  _tooltip: null,
  // 弹窗实例
  _popperInstance: null,
  // 显示弹窗
  show: ()=>{
    if(!instructionPopperInfo.isUserOk || !instructionPopperInfo.isTextOk) {
      return
    }
    if(!instructionPopperInfo.showNums){
      // 用户访问页面且弹窗显示的次数（页面周期内仅记录一次）
      var nums = instructionPopperInfo.getShowNums();
      instructionPopperInfo.setShowNums(nums+1)
    }
    instructionPopperInfo.showNums++;
    instructionPopperInfo._tooltip && instructionPopperInfo._tooltip.setAttribute('data-show', '');
    instructionPopperInfo._popperInstance && instructionPopperInfo._popperInstance.update();
  },
  // 隐藏弹窗
  hide: ()=>{
    instructionPopperInfo.isTextOk = false;
    instructionPopperInfo._tooltip && instructionPopperInfo._tooltip.removeAttribute('data-show');
    instructionPopperInfo._popperInstance && instructionPopperInfo._popperInstance.update();
  },
  // localStorage key值，记录用户访问页面且弹窗显示的次数
  key: 'b2cweb.jrdscef.home.instructionPopper',
  // 获取用户访问页面且弹窗显示次数
  getShowNums: ()=>{
    var val = localStorage.getItem(instructionPopperInfo.key);
    var _val = parseFloat(val)
    if (isNaN(_val)) {
        return 0
    }
    return _val
  },
  // 设置用户访问页面且弹窗显示次数
  setShowNums: (val)=>{
    localStorage.setItem(instructionPopperInfo.key,val);
  },
}
window.$onshow = true;
$(function () {

  app = new AppOpen({
    clientVer: 'jrds'
  })
  // 获取财富启航是否展示
  getIndexpendant()
  // 获取学习进度
  getWatchedProgress()
  //更改进度条数字
  //  var progress = Math.floor(Math.random()*10+80);
  $('#progress').html(Math.floor(Math.random() * 10 + 80) + "%");
  // var timerout;
  // if(!!window.ActiveXObject || "ActiveXObject" in window){

  // }else{
  // 	 for(var i = 70; i <= 100; i ++){
  // 		 	(function(i){
  // 				timerout = setTimeout(function(){
  // 						$('#progress').html(i+"%");
  // 				},50*(i-49));
  // 				//timeout();

  // 			})(i);
  // 	 }	
  // }

  //判断是否有皮肤cookie
  const skinCookieName = 'znb_' + dateHash + '_skinclass'
  const skinclassLocal = localStorage.getItem(skinCookieName)
  avatarType = skinclassLocal&&skinclassLocal.includes('blue')?'1':'0';
  initVtuber();
  let cssHref = location.protocol + staticLocation + 'theme-orange-bg.' + dateHash + '.min.css';
  if (skinclassLocal) {
    cssHref = skinclassLocal;
  }
  $('.skinclass').attr('href', cssHref);
  getCpmj()
  judgeSkin(cssHref);
  //判断是否有声音cookie
  if ($.cookie('vedio') == 'nomusic') {
    $('#vedioControl').addClass('bg-vedio-stop');
  }
  //换肤
  $('#changeSkin').click(function (e) {
    e.stopPropagation();
    $('#skinContent').show();
  });
  $('#skinContent').find('li').on({
    mouseover: function () {
      $(this).addClass('liskin').siblings().removeClass('liskin');
    },
    mouseout: function () {
      $(this).removeClass('liskin');
    },
    click: function (e) {
      var href = $(this).data('href');
      var name = $(this).find('a').text();
      switch (name) {
        case '土豪金':
          try {
            TA.log({
              id: 'jrds_58c2a520_58'
            });
            avatarType='0';
          } catch (e) {}
          break;
        case '高雅蓝':
          try {
            TA.log({
              id: 'jrds_58c2a532_817'
            });
            avatarType='1';
          } catch (e) {}
          break;
        case '翡翠金':
          try {
            TA.log({
              id: 'jrds_58c2a54b_852'
            });
            avatarType='2';
          } catch (e) {}
          break;
        case '金属蓝':
          try {
            TA.log({
              id: 'jrds_58c2a561_605'
            });
            avatarType='3';
          } catch (e) {}
          break;

      }
      $('.skinclass').attr('href', href);
      judgeSkin(href);
      localStorage.setItem(skinCookieName, href); //存到localStorage中
      setVirtualAvatarColor(avatarType);
      indexAnimate();
    }
  });

  $('#container').mouseover(function (e) {
    var $this = $(this);
    var $target = $(e.target);
    var $title = $target.find('.module-title');
    if ($target.hasClass('module-common')) {
      $title.stop().animate({
        'bottom': '10px',
        'fontSize': '20px'
      });
    }
  }).mouseout(function (e) {
    var $this = $(this);
    var $target = $(e.target);
    var $title = $target.find('.module-title');
    if ($target.hasClass('module-common')) {
      $title.stop().animate({
        'bottom': '4px',
        'fontSize': '18px'
      });
    }
  });
  $('body').on('click', function (e) {
    var $target = $(e.target);
    var id = $target.data('id');
    //var $teasingModal = $('#teasingModal');
    // try{
    // 	var thsQuote        = external.createObject('Quote');
    // 	var util            = external.createObject('Util');
    // }catch(e){}
    switch (id) {
      case 'teasing':
        try {
          TA.log({
            id: 'jrds_58c2a4ff_633'
          });
        } catch (e) {}
        $(document.body).addClass('modal-open');
        window.API.use({
          method: 'Util.openURL2',
          data: {
            url: location.protocol + '//vis.10jqka.com.cn/tgfw/feedback.html' + '?id=81',
            mode: 8,
            useCef: true
          }
        })
        /* $teasingModal.addClass('open').show();
        var date = new Date();
        $('#kefuDate').text(date.toLocaleString());
        $('#userQuestion').focus(function() {
            if ($(this).val() === $('#userQuestion').data('placehold')) {
                $(this).val('');
            }
            /*$(this).on('keydown',function(e){
            	if(e.which == 13){
            		e.preventDefault();
            		var userid = external.createObject('Passport').get('userid');
            		$('#userId').val(userid);
            		var result = $('#chartForm').serialize();
            		if($('#userQuestion').val() === '' || $('#userQuestion').val() === $('#userQuestion').data('placehold')){
            			customAlert('吐槽内容不能为空！');
            			return false;
            		}
            		sendMessage(result);
            	}
            });
        }).blur(function() {
            if ($(this).val() === '') {
                $(this).val($('#userQuestion').data('placehold'));
            }
            $(this).off('keydown');
        }); */

        break;
        /*  case 'close':
             $(document.body).removeClass('modal-open');
             $teasingModal.removeClass('open').hide();
             break; */
        /* case 'sendButton':
            e.preventDefault();
            if ($('#userQuestion').val().length > 200) {
                customAlert("请不要超过200字！");
                return false;
            }
            API.use({
                method: 'Passport.get',
                data: 'userid',
                success: function(userid) {
                    $('#userId').val(userid);
                    var result = $('#chartForm').serialize();
                    if ($('#userQuestion').val() === '' || $('#userQuestion').val() === $('#userQuestion').data('placehold')) {
                        customAlert('吐槽内容不能为空！');
                        return false;
                    }
                    sendMessage(result);
                }
            });
            // var userid = external.createObject('Passport').get('userid');

            break; */
      case 'trend': //点击大盘趋势
        try {
          TA.log({
            id: 'jrds_58c2a3d8_113'
          });
        } catch (e) {}
        // thsQuote.switchPage(12640);
        API.use({
          method: 'Quote.switchPage',
          data: 12640
        });
        break;
      case 'hot': //点击板块热点
        try {
          TA.log({
            id: 'jrds_58c2a3fc_454'
          });
        } catch (e) {}
        //thsQuote.switchPage(11654);
        //
        // API.use({
        //     method: 'Util.getHxVer',
        //     success: function(result) {
        //        var hxVersion = 'E020.00.00.0000';
        // 	   hxVersion =result;
        // 	   var hxVerArr = hxVersion.split('.');
        // 	   var formatVersion = hxVerArr[0].substr(3) + hxVerArr[1] + hxVerArr[2] + hxVerArr[3];
        // 	   if(formatVersion >= 860940013){
        // 	   		API.use({
        // 				method:'Quote.switchPage',
        // 				data:11897
        // 			});
        // 	   }else{
        // 			API.use({
        // 				method:'Quote.switchPage',
        // 				data:8763
        // 			});				   	
        // 	   }

        // 	}   
        // });
        API.use({
          method: 'Quote.switchPage',
          data: 8763
        });

        // thsQuote.switchPage(8710);
        break;
      case 'timing': //点击买卖时机
        try {
          TA.log({
            id: 'jrds_58c2a41f_154'
          });
        } catch (e) {}
        API.use({
          method: 'Quote.switchPage',
          data: 8799
        });
        //thsQuote.switchPage(12618);
        // thsQuote.switchPage(8799);
        break;
      case 'choose': //点击智能选股
        try {
          TA.log({
            id: 'jrds_58c2a43c_589'
          });
        } catch (e) {}
        API.use({
          method: 'Util.getHxVer',
          success: function (result) {
            var hxVersion = 'E020.00.00.0000';
            hxVersion = result;
            var hxVerArr = hxVersion.split('.');
            var formatVersion = hxVerArr[0].substr(3) + hxVerArr[1] + hxVerArr[2] + hxVerArr[3];
            if (formatVersion >= 860940017) {
              API.use({
                method: 'Quote.switchPage',
                data: 12595
              });
            } else {
              API.use({
                method: 'Quote.switchPage',
                data: 8765
              });
            }

          }
        });
        //恢复
        // API.use({
        // 	method:'Quote.switchPage',
        // 	data:8765
        // });
        // thsQuote.switchPage(8765);
        break;
      case 'pool': //点击理念股池
        try {
          TA.log({
            id: 'jrds_58c2a455_94'
          });
        } catch (e) {}
        API.use({
          method: 'Quote.changeContainerUrl',
          data: {
            id: 8670,
            name: '九维理念_内容',
            url: location.protocol + '//gpc.10jqka.com.cn/idea/index.html'
          }
        });
        //window.location.href="//gpc.10jqka.com.cn/idea/index.html";
        //thsQuote.switchPage(location.protocol+'//gpc.10jqka.com.cn/idea/index.html');
        // thsQuote.changeContainerUrl({
        // 	id:8670,
        // 	name:'九维理念_内容',
        // 	url:location.protocol+'//gpc.10jqka.com.cn/idea/index.html'
        // });
        //thsQuote.switchPage(8670);
        break;
      case 'combination': //点击投资组合
        try {
          TA.log({
            id: 'jrds_58c2a478_9'
          });
        } catch (e) {}
        API.use({
          method: 'Quote.changeContainerUrl',
          data: {
            id: 8775,
            name: '我的组合',
            url: location.protocol + '//vis.10jqka.com.cn/dzl/tzzh/index?jrds=1'
          }
        });
        //thsQuote.switchPage(8775);
        // thsQuote.changeContainerUrl({
        // 	id:8775,
        // 	name:'我的组合',
        // 	url:location.protocol+'//vis.10jqka.com.cn/dzl/tzzh/index?jrds=1'
        // });
        break;
      case 'data': //点击咨讯数据
        try {
          TA.log({
            id: 'jrds_58c2a49b_513'
          });
        } catch (e) {}
        API.use({
          method: 'Quote.switchPage',
          data: 8753
        });
        // thsQuote.switchPage(8753);
        break;
      case 'interest': //点击我的投顾
        try {
          TA.log({
            id: 'jrds_58c2a4b1_777'
          });
        } catch (e) {}
        //我的投顾版本控制
        API.use({
          method: 'Util.getHxVer',
          success: function (result) {
            var hxVersion = 'E020.00.00.0000';
            hxVersion = result;
            var hxVerArr = hxVersion.split('.');
            var formatVersion = hxVerArr[0].substr(3) + hxVerArr[1] + hxVerArr[2] + hxVerArr[3];
            if (formatVersion >= 860900000) {
              API.use({
                method: 'Quote.switchPage',
                data: 12491
              });
            } else {
              API.use({
                method: 'Quote.switchPage',
                data: 8772
              });
            }
          }
        });
        break;
      case 'global': //点击全球联动
        try {
          TA.log({
            id: 'jrds_58c2a4cc_592'
          });
        } catch (e) {}
        API.use({
          method: 'Quote.switchPage',
          data: 10027
        });
        // thsQuote.switchPage(10027);
        break;
      case 'allVedioControl':
        try {
          TA.log({
            id: 'jrds_58c5f48e_125'
          });
        } catch (e) {}
        if ($.cookie('vedio') == 'music' || $.cookie('vedio') == undefined) {
          $.cookie('vedio', 'nomusic', {
            expires: 365
          });
          $('#vedioControl').addClass('bg-vedio-stop');
        } else {
          $.cookie('vedio', 'music'); //存到cookie中
          $('#vedioControl').removeClass('bg-vedio-stop');
        }
        break;
      case 'userInfo':
        try {
          TA.log({
            id: 'jrds_58c2a4e8_342'
          });
        } catch (e) {}
        API.use({
          method: 'Util.openURL',
          data: [location.protocol + '//vis.10jqka.com.cn/dzl/instruction/index/version/jrds?win=1', 4]
        });
        // util.openURL(location.protocol+'//vis.10jqka.com.cn/dzl/instruction/index/version/jrds?win=1',4);
        break;
      case 'questions-one': //趋势看不懂
        API.use({
          method: 'Quote.switchPage',
          data: 8761
        });
        // thsQuote.switchPage(8761);
        break;
      case 'questions-two': //选股不会选？
        API.use({
          method: 'Quote.switchPage',
          data: 12595
        });
        // thsQuote.switchPage(12595);
        break;
      case 'questions-three': //买卖点把握不好？
        API.use({
          method: 'Quote.switchPage',
          data: 12618
        });
        // thsQuote.switchPage(12618);
        break;
      case 'questions-four': //我要收听课程！
        API.use({
          method: 'Quote.switchPage',
          data: 8767
        });
        // thsQuote.switchPage(8767);
        break;
      case 'questions-five':
        API.use({
          method: 'Util.openURL',
          data: [location.protocol + '//vote.10jqka.com.cn/webvote/43085c18d7afea7f88a1be0a0f23b6c3', 4]
        });
        break;
      case 'cpzg':
        app.open(8, location.protocol + '//gdzx.10jqka.com.cn/sfzx/cpzg/index/version/1?usecef=1')
        try {
          TA.log({
            id: 'jrds_5976e5bc_420'
          });
        } catch (e) {}
        // util.openURL(location.protocol+'//gdzx.10jqka.com.cn/sfzx/cpzg',8);	
        break;
      case 'cpmj':
        API.use({
          method: 'Util.openURL2',
          data: {url: location.protocol + "//erup.10jqka.com.cn/charge/traderesotericafront/html/index.html#/home?putway=popout", mode:8,useCef:true}
        });
        break;
      case 'yfw':
        API.use({
          method: 'Quote.changeContainerUrl',
          data: {
            id: 12491,
            name: '投顾服务',
            url: location.protocol + '//vis.10jqka.com.cn/tgfw/index.html#/study'
          }
        });
        break;
    }
  });
  //监听页面变化
  $(window).resize(function () {
    // setTimeout(wresize, 100);
    wresize();
    !popperInstance || popperInstance.update()
  });

  var cocoTimer = setInterval(getAd, 600000);
  getAd();
  $('#chartWindow').find('.opacity-1').addClass('opacity-4');

  setInstructionPopper();
});

// 将新人引导的关闭弹窗的情况存到cookie
function judgeStudyStep() {
  const userid = $.cookie('userid') || $.cookie('@#!userid!#@') || 0
  const studyStepLocalName = 'znb_' + dateHash + '_studyStep_' + userid
  let studyStep
  // 步骤对照关系
  // 0: '未关闭'
  // 1: '关闭第一个'
  // 2: '关闭第二个'
  const studyStepLocal = localStorage.getItem(studyStepLocalName)
  if (studyStepLocal) {
    studyStep = studyStepLocal
  } else {
    studyStep = 0
  }
  //更新cookie
  writeStudyStep(studyStep)
  return Number(studyStep)
}

function writeStudyStep(step = 0) {
  const userid = $.cookie('userid') || $.cookie('@#!userid!#@') || 0
  // 用于区分cookie对应前端代码版本，更新版本以后可以更改dateHash用于覆盖历史cookie
  const studyStepLocalName = 'znb_' + dateHash + '_studyStep_' + userid
  //更新cookie
  localStorage.setItem(studyStepLocalName, step);
}

//跑马灯（后续可以使用）
function getAd() {
  //首页跑马灯
  $.ajax({
    url: location.protocol + '//vis.10jqka.com.cn/dzl/interface/gethorsedata',
    type: 'POST',
    dataType: 'json',
    success: function (data) {


      if (data.errorcode === 0) {
        var result = data.result;
        var tpl = '<div class="horseContent2">';
        var link_address, url, version, type, tid;
        API.use({
          method: 'Util.getHxVer',
          success: function (r) {
            var hxVersion = 'E020.00.00.0000';
            hxVersion = r;
            var hxVerArr = hxVersion.split('.');
            var formatVersion = hxVerArr[0].substr(3) + hxVerArr[1] + hxVerArr[2] + hxVerArr[3];
            var isNew = false;
            if (formatVersion >= 86090000) {
              isNew = true;
            }
            for (var i = 0, len = result.length; i < len; i++) {
              link_address = result[i]['link_address'].split('-');
              url = '';
              version = '';
              type = 8;
              tid = ''
              if (result[i]['link_type'] === 0) {
                url = location.protocol + '//vis.10jqka.com.cn/dzl/xbtgcommon/video/menu/0/vtid/' + link_address[1] + '/vid/' + link_address[0] + '?win=1';
              } else if (result[i]['link_type'] === 1) {
                if (isNew) {
                  url = location.protocol + '//vis.10jqka.com.cn/tgfw/index.html#/article/' + link_address[0] + '/themeid/' + link_address[1] + '?usecef=1&win=1'
                  type = 13
                } else {
                  url = location.protocol + '//vis.10jqka.com.cn/dzl/xbtgcommon/article/menu/1/vtid/' + link_address[1] + '/aid/' + link_address[0] + '?win=1';
                }
              } else if (result[i]['link_type'] === 2) {
                url = location.protocol + '//vis.10jqka.com.cn/dzl/xbtgcommon/video/menu/1/vtid/' + link_address[1] + '/vid/' + link_address[0] + '?win=1';
              } else if (result[i]['link_type'] === 3) {
                url = location.protocol + '//vis.10jqka.com.cn/tgfw/index.html#/video/' + link_address[0] + '/themeid/' + link_address[1] + '?usecef=1&win=1'
                version = '8.60.94'
                type = 13
                tid = 'jrds_pmd_' + link_address[1] + '_' + link_address[0]
              } else {
                url = '###';
              }
              tpl += '<a class="ths_appopen" href="###" url="' + url + '" type="' + type + '" version="' + version + '" tid="' + tid + '" hidefocus="true" title="' + result[i]['title'] + '">' + result[i]['title'] + '</a>'

            }
            tpl += '</div>';
            tpl += tpl;
            $('#horseWrap').html(tpl)

            var wrapWidth = 0;
            $('.horseContent2').eq(0).find('a').each(function () {
              wrapWidth += $(this).outerWidth(true);
            });


            clearInterval(cocoTimer2);
            cocoTimer2 = setInterval(function () {
              if (window.$onshow) {
                startHorse("#horseWrap", "2", wrapWidth);
              }

            }, 100);
          }
        });

      }


    },
    error: function (e) {

    }
  });
}



//监听模态框和首页背景
function wresize() {
  var $mainWrapper = $('.main-wrapper');
  var $modalBackdrop = $('#conceptModal').find('.modal-backdrop');
  //var $teasBackdrop = $('#teasingModal').find('.modal-backdrop');
  var $img = $('#bgIndex').find('img');
  var scrollWidth = $(window).width();
  var scrollHeight = $(window).height();
  var modalHeight = $('#conceptModal').outerHeight();
  //var teasHeight = $('#teasingModal').outerHeight();
  var containerHeight = $('#container').outerHeight();
  var windowWidth = $('body').width();
  var $cpzg = $('#cpzg');
  var $yfw = $('#yfw');
  var $cpmj = $('#cpmj');
  var $xsyd = $('#xsyd');
  var $vtuber = $('#vtuber .broadcast-mini');

  //当主页宽度大于窗口宽度
  if (parseFloat(scrollWidth) <= 1193) {
    $mainWrapper.css({
      'justify-content': 'flex-start',
      'marginLeft': 20 + 'px'
    })
    $img.width(1193);
    $('body').width(1193);
    $('#changeSkin').css({
      'right': 0
    });
    $('#skinContent').css({
      'right': 0
    });
    $cpzg.css({
      'right': '80px'
    });
    $yfw.css({
      'right': '80px'
    });
    $cpmj.css({
      'right': '80px'
    });
    $xsyd.css({
      'right': '10px'
    });
    vtuberRight='14px';
    $vtuber.css({
      'right':vtuberRight
    });
    

    // popperInstance.destroy()
    // $('.popover').css({            
    //     'position': 'absolute',
    //     'right': '20px',
    //     'top': '440px',
    //     'margin': '0px'
    // })
    // $('.popover #arrow').css({
    //     'position': 'absolute',
    //     'bottom': '-5px',
    //     'right': '35px'
    // })

  } else if (parseFloat(scrollWidth) <= 1273) {
    $mainWrapper.css({
      'justify-content': 'flex-start',
      'marginLeft': 20 + 'px'
    })
    $img.width(1273);
    $('body').width(1273);
    $('#changeSkin').css({
      'right': '80px'
    });
    $('#skinContent').css({
      'right': '80px'
    });
    $cpzg.css({
      'right': '160px'
    });
    $yfw.css({
      'right': '160px'
    });
    $cpmj.css({
      'right': '160px'
    });
    $xsyd.css({
      'right': '90px'
    });
    vtuberRight='94px';
    $vtuber.css({
      'right':vtuberRight
    })

    // popperInstance.destroy()
    // $('.popover').css({            
    //     'position': 'absolute',
    //     'right': '100px',
    //     'top': '440px',
    //     'margin': '0px'
    // })
    // $('.popover #arrow').css({
    //     'position': 'absolute',
    //     'bottom': '-5px',
    //     'right': '35px'
    // })

  } else {
    $mainWrapper.css({
      'justify-content': 'center',
      'marginLeft': 0
    })
    $img.width(scrollWidth);
    $('body').width(scrollWidth);
    $('#changeSkin').css({
      'right': 0
    });
    $('#skinContent').css({
      'right': 0
    });
    $cpzg.css({
      'right': (scrollWidth - 1073) / 2 - 21 + 'px'
    });
    $yfw.css({
      'right': (scrollWidth - 1073) / 2 - 21 + 'px'
    });
    $cpmj.css({
      'right': (scrollWidth - 1073) / 2 - 21 + 'px'
    });
    $xsyd.css({
      'right': (scrollWidth - 1073) / 2 - 91 + 'px'
    });
    vtuberRight=(scrollWidth - 1073) / 2 - 89 + 'px';
    $vtuber.css({
      'right': vtuberRight
    });
  }
  if (parseFloat(containerHeight) >= parseFloat(scrollHeight)) {
    $img.height((containerHeight + 20) / 5);
  } else {
    $img.height(scrollHeight / 5);
  }
  //if (scrollHeight < modalHeight || scrollHeight < teasHeight) {
  if (scrollHeight < modalHeight) {
    $modalBackdrop.height(modalHeight);
    //$teasBackdrop.height(teasHeight);
  }
  //$teasBackdrop.width(scrollWidth);
  $modalBackdrop.css({
    'width': scrollWidth
  });

}
/* @ describetion  换肤
 * @ skinclass     换肤地址
 */
function judgeSkin(skinclass) {
  var $img = $('#bgIndex').find('img');
  var imgLength = $img.length;
  //var ie6       = !-[1,]&&!window.XMLHttpRequest;
  if (skinclass.indexOf('theme-blue.') > 0 || skinclass.indexOf('theme-orange-bg.') > 0) {
    ////i.thsi.cn/images/dzl/znbdzl/module-orange/bg-orange_01.jpg
    for (var i = 0; i < imgLength; i++) {
      $img.eq(i).attr('src', location.protocol + '//i.thsi.cn/images/dzl/znbdzl/module-blue/bg-blue_0' + (i + 1) + '.jpg');

    }
    // $('#containerBg').addClass('hide');
    // $('#containerBg2').removeClass('hide');


  } else {
    for (var i = 0; i < imgLength; i++) {
      $img.eq(i).attr('src', location.protocol + '//i.thsi.cn/images/dzl/znbdzl/module-orange/bg-orange_0' + (i + 1) + '.jpg');
    }
    //$('#containerBg').attr('src',location.protocol+'//i.thsi.cn/images/dzl/znbdzl/module-orange/bg-page.png');
    // $('#containerBg2').addClass('hide');
    // $('#containerBg').removeClass('hide');
  }

}
/* @ describetion  发送一条反馈信息
 * @ result        请求参数json对象
 */
function sendMessage(result) {
  $.support.cors = true;
  $.ajax({
    type: 'post',
    url: location.protocol + '//sp.10jqka.com.cn/liuyan/message/save',
    data: result,
    dataType: 'jsonp',
    success: function (data) {
      if (data.code === 0) {
        /**
         * TODO:
         *然后显示在页面上
         */
        addRecord();
        $('#answerAttachThings').val(''); //清空图片信息
        //setTimeout("addAnswer('好的，感谢您的意见或反馈，我会尽快帮您转告我们的工作人员！')",1300);
      } else {
        customAlert(data.message);
      }
    },
    error: function (data) {
      customAlert("网络异常!");
    }
  });
}
/* @ describetion  客服自动反馈
 * @ text          反馈内容
 */
function addAnswer(text) {
  var content = text;
  var date = new Date();
  var chartTmpl = '<div class="chart-info">' +
    '<div class="chart-pic fixpng "></div>' +
    '<div class="tooltip-wrap">' +
    '<div class="tooltips opacity-1">' +
    '<div class="tooltips-bg tooltips-bg-left"></div>' +
    '<div class="arrow arrow-left arrow-bg-left"></div>' +
    '</div>' +
    '<div class="chart-wrap-left">' +
    '<p class="chart-title"><span class="chart-date">' + date.toLocaleString() + '</span>机器人小AI</p>' +
    '<p class="chart-content">' + content + '</p>' +
    '</div>' +
    '</div>' +
    '</div>';
  calacDom(chartTmpl);
}
//新增一条用户信息
function addRecord(isImg) {
  var content;
  if (isImg) {
    var imgUrl = $('#answerAttachThings').val();
    content = '<img src="' + imgUrl + '" style="width:100%;">';

  } else {
    content = $('#userQuestion').val();
    $('#userQuestion').val('');
  }
  var date = new Date();
  var chartTmpl = '<div class="chart-info fr mr-10">' +
    '<div class="user-pic fr fixpng "></div>' +
    '<div class="tooltip-wrap fr">' +
    '<div class="tooltips opacity-4">' +
    '<div class="tooltips-bg tooltips-bg-right"></div>' +
    '<div class="arrow arrow-right arrow-bg-right"></div>' +
    '</div>' +
    '<div class="chart-wrap-right">' +
    '<p class="chart-title"><span class="chart-date">' + date.toLocaleString() + '</span>我</p>' +
    '<p class="chart-content">' + content + '</p>' +
    '</div>' +
    '</div>' +
    '</div>';
  calacDom(chartTmpl, isImg);
}
//将信息插入窗口
function calacDom(chartTmpl, isImg) {
  var $chartWindow = $('#chartWindow');
  $chartWindow.append(chartTmpl);
  var $lastChartInfo = $chartWindow.find('.chart-info:last');
  var $chartContent = $lastChartInfo.find('.chart-content');
  var $tooltips = $lastChartInfo.find('.tooltips');
  var titleHeight = $lastChartInfo.find('.chart-title').height();
  var contentHeight;
  if (isImg) {
    $chartContent.find('img').load(function () {
      contentHeight = $chartContent.innerHeight();
      $tooltips.css({
        'height': (contentHeight + titleHeight + 16)
      });
    });
  } else {
    contentHeight = $chartContent.innerHeight();
    $tooltips.css({
      'height': (contentHeight + titleHeight + 16)
    });
  }
  $chartWindow.scrollTop($chartWindow[0].scrollHeight);
}
//邮件动画
function emailAnimate() {
  $('#readyStart').hide();
  $(document.body).addClass('modal-open');
  var emailTmpl = '<div id="emailBackup" class="backdrop opacity-7">' +
    '<div class="fixback" data-id="email" data-target="conceptModal"></div>' +
    '<div id="emails" class="email fixpng" data-id="email" data-target="conceptModal"></div>' +
    '<p id="guideTxt" class="guide-txt"></p>' +
    '</div>';
  $(document.body).prepend(emailTmpl);
  var emailTimer = setInterval(emailChange, 500);
  var guideText = '来自华尔街的理念测试';
  var length = guideText.length;
  for (var i = 0; i < length; i++) {
    (function (i, guideText) {
      setTimeout(function () {
        var eachText = guideText.substring(i, i + 1);
        $('#guideTxt').append(eachText);
      }, 300 * i);
    })(i, guideText);
  }
  setTimeout(function () {
    play('logoMP');
  }, 500);
  play('showinfoMP');
}
//邮件闪光动画
function emailChange() {
  $('#emails').toggle();
}
//判断是否已经进行过理念测试
function isSign() {
  // try{
  // var userid = external.createObject('Passport').get('userid');
  API.use({
    method: 'Passport.get',
    data: 'userid',
    success: function (userid) {
      var obj = {
        "userid": userid
      };
      $.support.cors = true;
      $.ajax({
        type: 'get',
        url: location.protocol + '//vis.10jqka.com.cn/dzl/interface/getuserln',
        data: obj,
        dataType: 'json',
        success: function (data) {
          if (data.result.inves == '') { //表示该用户没有进行过理念测试
            $('#isSign').val('0');
          } else {
            $('#isSign').val('1'); //1表示该用户已经进行过理念测试
          }
          wresize();
          indexAnimate();
        },
        error: function (data) {
          customAlert("网络异常！");
          $('#isSign').val('1');
          wresize();
          indexAnimate();
          return false;
        }
      });
    },
    error: function () {
      $('#isSign').val('1');
      wresize();
      indexAnimate();
    },
    timeout: 3000,
    timeoutFunction: function () {
      $('#isSign').val('1');
      wresize();
      indexAnimate();
    },
    notClient: function () {
      $('#isSign').val('1');
      wresize();
      indexAnimate();
    }
  });
}

//首页动画
function indexAnimate() {
  if ($('#container').is(':animated')) {
    return;
  }
  $('#readyStart').hide();
  $(document.body).removeClass('modal-open');
  var scrollWidth = $(window).width();
  var windowWidth = $('body').width();
  var $mainWrapper = $('.main-wrapper');
  var $container = $('#container');
  var $module = $('#module');
  var $logo = $('#logo');
  var $logoTitle = $('#logoTitle');
  var $cpzg = $('#cpzg');
  var $yfw = $('#yfw');
  var $cpmj = $('#cpmj');
  var $xsyd = $('#xsyd');
  var $vtuber = $('#vtuber .broadcast-mini')
  var $btnGroup = $container.find('.btn-group');
  var containerHeight = $container.height();
  var containerWidth = $container.width();
  var moduleHeight = $module.height();
  var logoHeight = $logo.height();
  var logoTitleWidth = $logoTitle.width();
  var btnGroupHeight = $btnGroup.height();
  // var cpzgHeight      = $cpzg.height(); 
  // var yfwHeight       = $yfw.height(); 
  // var cpmjHeight      = $cpmj.height(); 
  var cpzgHeight = 84;
  var yfwHeight = 84;
  var cpmjHeight = 84;
  var xsydWidth = 100;
  var vtuberWidth = 82;
  $container.css({
    'width': '0'
  });
  $module.css({
    'height': 0,
    'top': '60%'
  });
  $logo.css({
    'height': 0
  });
  $logoTitle.css({
    'width': 0
  });
  $btnGroup.css({
    'height': 0
  });
  // hide popper
  instructionPopperInfo.hide();

  //当主页宽度大于窗口宽度时不同的初始化状态
  if (parseFloat(scrollWidth) <= 1193) {
    $mainWrapper.css({
      'justify-content': 'flex-start',
      'marginLeft': 20 + 'px'
    })
    $('body').width(1193);
    $cpzg.css({
      'height': 0,
      'display': 'none',
      'right': '80px'
    });
    $yfw.css({
      'height': 0,
      'display': 'none',
      'right': '80px'
    });
    $cpmj.css({
      'height': 0,
      'display': 'none',
      'right': '80px'
    });
    vtuberTop='556px';
    vtuberRight='49px';
    $vtuber.css({
      'width': 0,
      'display': 'none',
      'top': vtuberTop,
      'right': vtuberRight
    });
    $xsyd.css({
      'width': 0,
      'display': 'none',
      'top': '460px',
      'right': '45px'
    });
  } else if (parseFloat(scrollWidth) <= 1273) {
    $mainWrapper.css({
      'justify-content': 'flex-start',
      'marginLeft': 20 + 'px'
    })
    $('body').width(1273);
    $('#changeSkin').css({
      'right': '100px'
    });
    $cpzg.css({
      'height': 0,
      'display': 'none',
      'right': '160px'
    });
    $yfw.css({
      'height': 0,
      'display': 'none',
      'right': '160px'
    });
    $cpmj.css({
      'height': 0,
      'display': 'none',
      'right': '160px'
    });
    $xsyd.css({
      'width': 0,
      'display': 'none',
      'top': '460px',
      'right': '135px'
    });
    vtuberTop='556px';
    vtuberRight='139px';
    $vtuber.css({
      'width': 0,
      'display': 'none',
      'top': vtuberTop,
      'right': vtuberRight
    });
  } else {
    $mainWrapper.css({
      'justify-content': 'center',
      'marginLeft': 0
    })
    $('body').width(scrollWidth);
    $cpzg.css({
      'height': 0,
      'display': 'none',
      'right': (windowWidth - containerWidth) / 2 - 21 + 'px'
    });
    $yfw.css({
      'height': 0,
      'display': 'none',
      'right': (windowWidth - containerWidth) / 2 - 21 + 'px'
    });
    $cpmj.css({
      'height': 0,
      'display': 'none',
      'right': (windowWidth - containerWidth) / 2 - 21 + 'px'
    });
    $xsyd.css({
      'width': 0,
      'display': 'none',
      'top': '460px',
      'right': (windowWidth - containerWidth) / 2 - 45 + 'px'
    });
    vtuberTop='556px';
    vtuberRight=(windowWidth - containerWidth) / 2 - 41 + 'px';
    $vtuber.css({
      'width': 0,
      'display': 'none',
      'top': vtuberTop,
      'right': vtuberRight
    });
  }


  //切换右侧 操盘总纲+AI云服务 的字体颜色
  var $thsSkin = $('.skinclass').attr('href');
  if ($thsSkin.indexOf('orange.') > -1) {
    $('#cpzg').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
    $('#yfw').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
    $('#cpmj').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
  } else if ($thsSkin.indexOf('blue.') > -1) {
    $('#cpzg').css('border', '2px solid #608bbf').find('a').css('color', '#90dbef').attr('c-color', '#90dbef');
    $('#yfw').css('border', '2px solid #608bbf').find('a').css('color', '#90dbef').attr('c-color', '#90dbef');
    $('#cpmj').css('border', '2px solid #608bbf').find('a').css('color', '#90dbef').attr('c-color', '#90dbef');
  } else if ($thsSkin.indexOf('orange-bg.') > -1) {
    $('#cpzg').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
    $('#yfw').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
    $('#cpmj').css('border', '2px solid rgb(123, 98, 59)').find('a').css('color', '#f6d16f').attr('c-color', '#f6d16f');
  } else if ($thsSkin.indexOf('blue-bg.') > -1) {
    $('#cpzg').css('border', '2px solid #0c9a96').find('a').css('color', '#0f9e98').attr('c-color', '#0f9e98');
    $('#yfw').css('border', '2px solid #0c9a96').find('a').css('color', '#0f9e98').attr('c-color', '#0f9e98');
    $('#cpmj').css('border', '2px solid #0c9a96').find('a').css('color', '#0f9e98').attr('c-color', '#0f9e98');
  }
  $('#cpzg a').on('mouseenter', function () {
    $(this).css('color', '#fff');
  }).on('mouseleave', function () {
    $(this).css('color', $(this).attr('c-color'));
  });
  $('#yfw a').on('mouseenter', function () {
    $(this).css('color', '#fff');
  }).on('mouseleave', function () {
    $(this).css('color', $(this).attr('c-color'));
  });
  $('#cpmj a').on('mouseenter', function () {
    $(this).css('color', '#fff');
  }).on('mouseleave', function () {
    $(this).css('color', $(this).attr('c-color'));
  });
  var isShowAI = false;
  var intervalAI;
  var queues = [
    function () {
      $('.email-backdrop').show(); //动画运行过程中，防止点击
      $container.stop(false, true).animate({
        'width': containerWidth
      }, 'slow', aniNext);
      play('jiugonggeMP');
    },
    function () {
      $module.stop(false, true).animate({
        'height': moduleHeight,
        'top': '164px'
      }, 'slow', aniNext);
    },
    function () {
      $logo.stop(false, true).animate({
        'height': logoHeight
      }, 'slow', aniNext);
      $logoTitle.stop(false, true).animate({
        'width': logoTitleWidth
      }, 'slow', aniNext);
    },
    function () {
      $cpzg.css({
        'display': 'block'
      });
      $cpzg.stop(false, true).animate({
        'height': cpzgHeight
      }, 'slow', aniNext);
    },
    function () {
      $yfw.css({
        'display': 'block'
      });
      $yfw.stop(false, true).animate({
        'height': yfwHeight
      }, 'slow', aniNext);
    },
    function () {
      if(hasCpmj){
        $cpmj.css({
          'display': 'block'
        });
      }
      $cpmj.stop(false, true).animate({
        'height': cpmjHeight
      }, 'slow', aniNext);
    },
    function () {
      if(cfqhDisabled) {
        aniNext()
        return
      }

      $xsyd.css({
        'display': 'block'
      });
      if (parseFloat(scrollWidth) <= 1193) {
        $xsyd.stop(false, true).animate({
          'width': xsydWidth,
          'right': 0
        }, 'slow', aniNext);
      } else if (parseFloat(scrollWidth) <= 1273) {
        $xsyd.stop(false, true).animate({
          'width': xsydWidth,
          'right': '80px'
        }, 'slow', aniNext);
      } else {
        $xsyd.stop(false, true).animate({
          'width': xsydWidth,
          'right': (windowWidth - containerWidth) / 2 - 90 + 'px'
        }, 'slow', aniNext);
      }
    },
    function () {
      if(cfqhDisabled) {
        aniNext()
        return
      }

      cfqhAnimation()
    },
    function(){
      // 大屏模式下更换皮肤不用展示
      if(window.vtuberIns&&window.vtuberIns.getIsMini()){
        $('#vtuber>.vtuber-comp').css({
          display:'block'
        });
        $vtuber.css({
          'display': 'block'
        });
      }
      if (parseFloat(scrollWidth) <= 1193) {
        vtuberRight=0;
      } else if (parseFloat(scrollWidth) <= 1273) {
        vtuberRight='84px';
      } else {
        vtuberRight=(windowWidth - containerWidth) / 2 - 86 + 'px';
      }
      $vtuber.stop(false, true).animate({
        'width': vtuberWidth,
        'right': vtuberRight,
      }, 'slow', aniNext);
      $('#vtuber>.vtuber-comp')[0].style.setProperty('--vtuberTop',vtuberTop)
      $('#vtuber>.vtuber-comp')[0].style.setProperty('--vtuberRight',vtuberRight)
    },
    function () {
      $btnGroup.stop(false, true).animate({
        'height': btnGroupHeight
      },'normal','swing',aniNext);
      
      if ($('#isSign').val() == '0') {
        emailAnimate();
      }
      $('.email-backdrop').hide();
      
    },
    function () {
      instructionPopperInfo.isTextOk = true;
      instructionPopperInfo.show();
    }
  ];
  var aniNext = function () {
    $container.dequeue('myAnimation');
  };
  $container.queue('myAnimation', queues);
  aniNext();
}
function getDomain(){
  var arr = location.hostname.split('.');
  return arr.slice(1).join(".");
}
// 操盘秘籍运营，根据接口判断有无权限
function getCpmj() {
	var url =  `//apigate.${getDomain()}/d/charge/zxapi/cpmj/v1/auth`;
  // 接口Yapi http://software.myhexin.com/yapi/service/310643/interface/api/353956
  $.ajax({
    url,
    dataType: "json",
    xhrFields: {
      withCredentials: true,
    },
    success: function (rst) {
		try {
				hasCpmj = rst.data.auth;
		} catch (error) {
      hasCpmj = false;
			window.ClientMonitor.reportFrameErrors(
			{
				category: 'js', // 类型
				grade: 'Warning', // 级别
			},
			{
				name: `${url}接口错误参数错误`,
				message:error.message,
				stack:error.stack,
			}
    	);
		}
    },
	error: function(error){
    hasCpmj = false;
		window.ClientMonitor.reportFrameErrors(
			{
				category: 'ajax', // 类型
				grade: 'Warning', // 级别
			},
			{
				name: `${url}接口请求错误`,
				message:error.message,
				stack:error.stack,
			}
    	);
	}
  });
}
//跑马灯（后续可以使用）
function startHorse(ele, speed, width) {
  var $horseContent = $(ele);
  var speed = parseFloat(speed);
  var marginLeft = parseFloat($horseContent.css('marginLeft'));
  //var width         = parseInt($horseContent.css('width'));
  //var firstA        = $horseContent.find('a:first');
  //var firstWidth    = firstA.width();


  if (Math.abs(marginLeft) != 0 && (Math.abs(marginLeft) % width == 0 || Math.abs(marginLeft) % width == 1)) {

    $horseContent.css('marginLeft', 0);
    return;
  }
  $horseContent.css({
    'marginLeft': (marginLeft - speed) + 'px'
  });
}

//播放音乐
function play(ele) {
  if ($.cookie('vedio') == 'music' || $.cookie('vedio') == undefined) {
    try {
      if (navigator.userAgent.indexOf('MSIE') <= 0) {
        document.getElementById(ele + 'A').play();
      } else {
        document.getElementById(ele).play();
      }
      //document.getElementById(ele).play();
    } catch (e) {}
  }
}

function stop(ele) {
  try {
    if (navigator.userAgent.indexOf('MSIE') <= 0) {
      document.getElementById(ele + 'A').stop();
    } else {
      document.getElementById(ele).stop();
    }
    //document.getElementById(ele).stop();
  } catch (e) {}
}

function upfile() {
  var fileValue = $('#upfile').val();
  var fileValueArr = fileValue.split('\\');
  var fileName = fileValueArr[fileValueArr.length - 1];
  var fileNameArr = fileName.split('.');
  var filetype = fileNameArr[fileNameArr.length - 1];
  filetype = filetype.toLowerCase();
  var allowType = 'jpg|jpeg|gif|png';
  if (allowType.indexOf(filetype) == -1) {
    customAlert('请发送.jpg .jpeg .gif .png图片类型');
    return;
  }
  var uploadUrl = location.protocol + '//vis.10jqka.com.cn/fileupload/index/upload/?apiName=neican&apiCode=0&uploadType=2&waterMark=1';
  //var uploadUrl = location.protocol+'//i.10jqka.com.cn/Fileupload/index/upload/?apiName=neican&apiCode=0&uploadType=2';
  $.ajaxFileUpload({
    url: uploadUrl,
    fileElementId: 'upfile',
    dataType: 'json',
    type: 'get',
    async: false,
    secureuri: false,
    success: function (result, status) {
      if (result.errorcode == 0) {
        var imgUrl = result.result.url;
        $('#answerAttachThings').val(imgUrl); //将信息赋值到该字段中
        addRecord(1);
        //setTimeout("addAnswer('好的，感谢您的意见或反馈，我会尽快帮您转告我们的工作人员！')",1300);
      } else {
        customAlert('上传图片异常，请重试');
      }
    },
    error: function (data, status, e) {
      //$('#imgIndex' + self.imgIndex).attr('src', location.protocol+'//i.thsi.cn/images/liuyan/auto/robot3/fail.jpg');
      customAlert('上传图片失败，请重试');
    }

  });
}

// 获取财富启航学习状态
function getWatchedProgress() {
  $.ajax({
    url: '//vis.10jqka.com.cn/tgfw/learningcenter/showuserwatchedprogress',
    type: 'get',
    data: {
      sid: 5
    },
    dataType: 'json',
    success: function (res) {
      let progress
      if (res.errorcode == 0) {
        const data = res.result || {}
        progress = data.progress || 0
      } else {
        progress = 0
      }
      watchProgress = progress
    },
    error: function (err) {
      watchProgress = 0
    }
  })
}

// 获取财富启航入口是否展示
function getIndexpendant() {
  $.ajax({
    url: '//vis.10jqka.com.cn/tgfw/learningcenter/showindexpendant',
    type: 'get',
    data: {
      sid: 5
    },
    dataType: 'json',
    success: function (res) {
      let display
      if (res.errorcode == 0) {
        const data = res.result || {}
        display = data.display || false
      } else {
        display = false
      }
      cfqhDisabled = !display
    },
    error: function (err) {
      cfqhDisabled = true
    }
  })
}
function judgeChrome49() {
  const chromeVersion = /Chrome\/([0-9.]+)/.exec(navigator.userAgent);
  if (chromeVersion) {
    var versionNumber = parseInt(chromeVersion[1].split('.')[0]);
    return versionNumber === 49;
  }
  return false;
}
// 初始化虚拟人
function initVtuber() {
  try {
    var sdkName=judgeChrome49()?'svelteSdkChrome49':'svelteSdk';
    window.vtuberIns = new window[sdkName].vtuber({
      target: $('#vtuber')[0],
      props: {
        miniDragable: false,
        position: {
          min: {},
          max: {
            bottom: '24px',
            right: '24px',
          },
        },
        avatarType: avatarType,
      },
    });
  } catch (error) {
    window.ClientMonitor.reportFrameErrors(
      {
        category: 'js',
        grade: 'Error',
      },
      {
        message: error.message,
        name: '初始化虚拟人报错' + error.name,
        stack: error.stack,
      }
    );
  }
}

// 设置虚拟人头像颜色
function setVirtualAvatarColor(avatarTypeParam) {
  try{
    window.vtuberIns.$$set({avatarType:avatarTypeParam});
  }catch(error){
    window.ClientMonitor.reportFrameErrors(
    {
      category: "js",
      grade: "Error"
    },
    {
      message: error.message,
      name: '虚拟人设置头像颜色报错'+error.name,
      stack: error.stack
    }
  );
  }
}

//这里用window.onload的原因是等待所有图片和页面所有元素加载完成之后执行；
// window.onload = function(){

setTimeout(function () {
  $('#readyImg').css({
    'backgroundPosition': '-278px 0'
  });
  // if(timerout){
  // 	clearTimeout(timerout);
  // }
  $('#progress').text('100%');
}, 500);
setTimeout(function () {
  //clearInterval(loadTimer);
  // $('#readyStart').find('.ready-box').addClass('v-hide');//隐藏wifi
  // $('#readyStart').find('.loading').removeClass('v-hide');//出现进度条
  $('#container').removeClass('v-hide');
  // setTimeout(function(){
  // 	play('loginMP');
  // },500);
  //正式环境

  // setTimeout(isSign,500);
  isSign();
  //判断用户是否在当前页面
  var sessionId = API.createSessionId('external');
  API.use({
    method: 'external.registerEvent',
    data: 'onshow',
    persistent: true,
    sessionId: sessionId,
    callbackName: 'onshow',
    success: function (data) {
      if (!data) {

        $('body').hide();
        window.$onshow = false;
      } else {

        $('body').show();
        window.$onshow = true;
      }
    }
  });

  //测试环境
  // setTimeout(function(){
  // 	$('#isSign').val('1');   //1表示该用户已经进行过理念测试
  // 	wresize();
  // 	indexAnimate();
  // },1500);
}, 1000);


// 财富启航动画
function cfqhAnimation() {
  const button = document.querySelector('#xsyd')
  const tooltip = document.querySelector('.popover.popover-xsyd')
  const $popover = $('.popover.popover-xsyd')
  const $title = $popover.find('.title')
  const $text = $popover.find('.content')
  const $button = $popover.find('.footer')
  const tooltipText = {
    0: {
      title: '财富启航',
      text: '助您看懂大盘、管理仓位、抓住主线、选对个股、把握买卖。',
      button: '我知道了'
    },
    1: {
      title: '再接再厉',
      text: '您已经完成部分课程学习，坚持让付出从一开始就变成收获！',
      button: '继续加油'
    },
    2: {
      title: '财富启航',
      text: '助您看懂大盘、管理仓位、抓住主线、选对个股、把握买卖。',
      button: ''
    }
  }
  // 是否可以允许移入移出控制显示
  let canPopClose = false,
    // 是否是第一次初始化，在不允许控制显示时，第一次初始化时需要点击关闭按钮才能允许控制
    firstInit = true
  let studyStep = judgeStudyStep()
  let nowStep = 0

  // 初始化popover
  popperInstance = Popper.createPopper(button, tooltip, {
    placement: 'top-start',
    modifiers: [{
        name: 'offset',
        options: {
          offset: [0, 10],
        },
      },
      {
        name: 'eventListeners',
        enabled: false
      },
    ],
  })

  function show() {
    if (!(canPopClose || firstInit)) {
      firstInit = false
      return
    }
    // Make the tooltip visible
    tooltip.setAttribute('data-show', '');

    // Enable the event listeners
    popperInstance.setOptions((options) => ({
      ...options,
      modifiers: [
        ...options.modifiers,
        // { name: 'eventListeners', enabled: true },
      ],
    }));

    // Update its position
    popperInstance.update();
  }
  // 初始化时展示
  show()

  function hide() {
    if (!canPopClose) return
    // Hide the tooltip
    tooltip.removeAttribute('data-show');

    // Disable the event listeners
    popperInstance.setOptions((options) => ({
      ...options,
      modifiers: [
        ...options.modifiers,
        // { name: 'eventListeners', enabled: false },
      ],
    }));
  }

  function closePop() {
    canPopClose = true
    hide()
  }

  // 对不同的新手引导学习情况进行处理
  if (watchProgress >= 0.5 && watchProgress < 1) {
    switch (studyStep) {
      case 0:
        nowStep = 1
        break
      case 1:
        nowStep = 1
        break
      case 2:
        nowStep = 2
        canPopClose = true
        hide()
        break
    }
  } else if (watchProgress == 1) {
    nowStep = 2
    canPopClose = true
    hide()
  } else {
    switch (studyStep) {
      case 1:
        nowStep = 1
        canPopClose = true
        hide()
        break
      default:
        nowStep = 0
        break

    }
  }
  if (watchProgress < 1) {
    $('.xsyd').addClass('active')
  }

  function changeToolTip() {
    if (canPopClose) {
      $title.text(tooltipText[2].title)
      $text.text(tooltipText[2].text)
      $button.text('')
    } else {
      $title.text(tooltipText[nowStep].title)
      $text.text(tooltipText[nowStep].text)
      $button.text(tooltipText[nowStep].button)
    }
  }
  changeToolTip()
  const clickPopover = function (e) {
    if (!canPopClose) {
      nowStep++
    }
    closePop()
    changeToolTip()
    writeStudyStep(nowStep)
  }
  // 点击关闭popover并允许控制
  $('.popover.popover-xsyd .footer').one({
    click: function (e) {
      e.stopPropagation();
      clickPopover()
    }
  })
  const changeSkin = function (e) {
    closePop()
    $('.popover.popover-xsyd').css({
      'display': 'none'
    })
    popperInstance.destroy()
    showEvents.forEach((event) => {
      button.removeEventListener(event, show);
    });

    hideEvents.forEach((event) => {
      button.removeEventListener(event, hide);
    });
    $('#skinContent').find('li').off('click', changeSkin)
    $('#xsyd').off('click', jumpToXsyd)
  }
  // 切换皮肤时注销popover以及监听
  $('#skinContent').find('li').on('click', changeSkin)

  const jumpToXsyd = function (e) {
    e.stopPropagation();
    clickPopover()
    API.use({
      method: 'Quote.changeContainerUrl',
      data: {
        id: 12491,
        name: '投顾服务',
        url: location.protocol + '//vis.10jqka.com.cn/tgfw/index.html#/study/cfqh'
      }
    });
  }
  $('#xsyd').on('click', jumpToXsyd)

  const showEvents = ['mouseenter', 'focus'];
  const hideEvents = ['mouseleave', 'blur'];

  showEvents.forEach((event) => {
    button.addEventListener(event, show);
  });

  hideEvents.forEach((event) => {
    button.addEventListener(event, hide);
  });

  $(window).scroll(function () {
    !popperInstance || popperInstance.update()
    console.log(scroll)
  })
}

// 设置浮窗
// 1、默认展示一个月，7月1日下线该浮窗；
// 2、用户打开“金融大师首页”页面前三次展示，后续不再展示；
// 3、6月1日后的用户不展示该浮窗；
function setInstructionPopper() {
  window.API.use({
    method: "Quote.getServerTime",
    success: function(result) {
        serverTimeCallback(result * 1000);
    },
    error: function(ecode, emsg) {
        serverTimeCallback(+new Date(), ecode + " : " + emsg);
    },
    notClient: function() {
        serverTimeCallback(+new Date());
    }
  });
  // 客户端时间回调
  function serverTimeCallback(result) {
    //  默认展示一个月，7月1日下线该浮窗；
    var deadTime = new Date('2022-07-01 00:00:00').getTime();
    if(result<deadTime){
      var nums = instructionPopperInfo.getShowNums();
      if(nums<3){
        getUserFuncTime();
      }
    }
  }
  // 获取用户是否是6/1号后的用户
  function getUserFuncTime() {
    // // 测试环境
    // var url = "//apigate.10jqka.com.cn/d/charge/backtest/auth/server/v1/function_time/15"
    // 正式环境
    var url = "//apigate.10jqka.com.cn/d/charge/backtest/auth/server/v1/function_time/4"

    $.ajax({
      url: url,
      type: "get",
      // 允许跨域
      crossDomain: true,
      // 下面这句话允许跨域的cookie访问
      xhrFields: {
          withCredentials: true
      },
      dataType: "json",
      success: function(res) {
          var lineTime = new Date('2022-06-01 00:00:00').getTime();
          if(res && res.status_code===0 && res.data && res.data.function_time) {
              if(new Date(res.data.function_time).getTime()<lineTime) {
                  funcTimeCallback(true);
              } else {
                  funcTimeCallback(false);
              }
          } else {
            funcTimeCallback(true);
          }
      },
      error: function(error) {
        funcTimeCallback(true);
      }
    })
  }
  // 6月1日后的用户不展示该浮窗；// @params {Boolean} result 是否是2022/06/01前的老用户 
  function funcTimeCallback(result) {
    if(result){
      instructionPopperInfo.isUserOk = true;
      initPopper();
      instructionPopperInfo.show();
    }
  }
  // 初始化弹窗
  function initPopper() {
    // 弹窗 元素
    const _button = document.querySelector('#instruction')
    instructionPopperInfo._tooltip = document.querySelector('.popover-instruction')
    // 初始化popover
    instructionPopperInfo._popperInstance = Popper.createPopper(_button, instructionPopperInfo._tooltip,{
      placement: 'bottom-end',
      modifiers: [{
        name: 'offset',
        options: {
          offset: [20, 15],
        },
      },
      {
        name: 'eventListeners',
        enabled: false
      },
    ],
    })
    instructionPopperInfo._popperInstance.update();
  }
}